<template>
  <div>
    <el-upload class="avatar-uploader" action :show-file-list="false" :http-request="customUpload">
      <img v-if="imgUrl" :src="imgUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import { uploadImg } from '@/api/merchant-admin'
export default {
  props: {
    imgUrl: {
      type: String,
      required: true
    },
    callback: {
      type: Function,
      required: true
    },
    imgType: {
      type: String,
      required: true,
      default: ''
    },
    paramKey: {
      type: String,
      required: true,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    customUpload({ file }) {
      const { type, size } = file
      const isLt2M = size / 1024 / 1024 > 2
      if (!type.includes('image')) {
        this.$message({
          type: 'error',
          message: '请上传图片'
        })
        return
      }
      if (isLt2M) {
        this.$message({
          type: 'error',
          message: '图片大小超出最大限制2M'
        })
      } else {
        let params = new FormData()
        params.append('image', file)
        params.append('type', this.imgType)
        uploadImg(params).then(({ id, url }) => {
          this.callback({
            url,
            id,
            key: this.paramKey
          })
        })
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>